package br.com.ac.fatureweb.utilitary.converter;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.inject.Named;

@Named
@FacesConverter("competenciaConverter")
public class CompetenciaConverter implements Converter {

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * javax.faces.convert.Converter#getAsObject(javax.faces.context.FacesContext
	 * , javax.faces.component.UIComponent, java.lang.String)
	 */
	@Override
	public Object getAsObject(final FacesContext ctx,
			final UIComponent uiComponent, final String value) {

		if (value != null && !value.isEmpty() && value.length() == 7) {
			if ((value.substring(3) + value.substring(0, 2)).equals("000000")) {
				return null;
			}
			return new Long(value.substring(3) + value.substring(0, 2));
		}
		return null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * javax.faces.convert.Converter#getAsString(javax.faces.context.FacesContext
	 * , javax.faces.component.UIComponent, java.lang.Object)
	 */
	@Override
	public String getAsString(final FacesContext ctx,
			final UIComponent uiComponent, final Object value) {
		if (value instanceof String) {

			if (value != null && ((String) value).length() > 0
					&& ((String) value).length() == 6) {
				final String newValue = (String) value;

				return newValue.substring(4) + "/" + newValue.substring(0, 4);
			}
		}

		if (value instanceof Long) {
			if (value != null && (Long) value != 0) {
				final String newValue = value.toString();

				if (newValue.length() == 6) {
					return newValue.substring(4) + "/"
							+ newValue.substring(0, 4);
				}

				return newValue;
			}
		}

		return "";
	}

}
